package com.aaa.marketresearch.dataresource.dao;

import com.aaa.marketresearch.dataresource.domain.Family;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * @author Nail
 */

@Repository
public class FamilyDAOImpl implements FamilyDAO {

    private static final Logger log = LoggerFactory.getLogger(FamilyDAOImpl.class);

    @PersistenceContext
    private EntityManager em;

    @Override
    public List<Family> getAll() {
        List<Family> result = em.createQuery("FROM Family f").getResultList();
        return result;
    }

    @Override
    public Family getById(Integer id) {
        final String query = "FROM Family f WHERE f.id=:id";

        Object obj = em.createQuery(query).setParameter("id", id).getSingleResult();
        if (obj != null) {
            return (Family) obj;
        } else {
            return null;
        }
    }

    @Override
    public Family getByEmail(String email) {
        final String query = "FROM Family f WHERE f.email=:email";

        Object obj = null;
        try {
            obj = em.createQuery(query).setParameter("email", email).getSingleResult();
        } catch (NonUniqueResultException ex) {
            return null;
        }
        return (Family) obj;

    }

    @Override
    public void save(Family family) {
        if (family.getId() == null) {
            this.em.persist(family);
        } else {
            this.em.merge(family);
        }
    }

    @Override
    public boolean delete(Integer id) {
        final String query = "DELETE Family f WHERE f.id = :id";
        int count = em.createQuery(query).setParameter("id", id).executeUpdate();
        return (count > 0);
    }
}
